﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace RHD.Web.Infrastructure {
	public static class ScriptManager {
		public static void RenderScripts(this HtmlHelper htmlHelper) {
			TempDataDictionary TempData = htmlHelper.ViewContext.TempData;
			IList<string> list = new List<string>();

			if (htmlHelper.ViewContext.TempData[ViewDataKeys.SCRIPT_MANAGER] != null) {
				list = list.Union((List<string>)TempData[ViewDataKeys.SCRIPT_MANAGER]).ToList();
				TempData[ViewDataKeys.SCRIPT_MANAGER] = null;
			}

			if (TempData[ViewDataKeys.SUCCESS_MESSAGE] != null) {
				foreach (string item in (IList<string>)TempData[ViewDataKeys.SUCCESS_MESSAGE]) {
					list.Add(string.Format("$.NotificationInfo('{0}');", item));
				}
				TempData[ViewDataKeys.SUCCESS_MESSAGE] = null;
			}

			if (TempData[ViewDataKeys.ERROR_MESSAGE] != null) {
				foreach (string item in (IList<string>)TempData[ViewDataKeys.ERROR_MESSAGE]) {
					list.Add(string.Format("$.NotificationError('{0}');", item));
				}
				TempData[ViewDataKeys.ERROR_MESSAGE] = null;
			}

			htmlHelper.ViewContext.Writer.Write("<script type='text/javascript'>");
			foreach (string item in list) {
				htmlHelper.ViewContext.Writer.Write(item);
			}
			htmlHelper.ViewContext.Writer.Write("</script>");
		}

		public static void AddScript(this HtmlHelper htmlHelper, string script) {
			IList<string> list = (List<string>)htmlHelper.ViewContext.TempData[ViewDataKeys.SCRIPT_MANAGER] ?? new List<string>();
			list.Add(script);
			htmlHelper.ViewContext.TempData[ViewDataKeys.SCRIPT_MANAGER] = list;
		}
	}
}